<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import type { chapterForm, chapterRequest, pointForm, pointWithQuestionsForm } from '@/api/type';
import { createChapter1 } from "@/api/course";
import { useUserStore } from '@/stores/user';
import { ElMessage, ElMessageBox } from 'element-plus';
let props = defineProps(['closechaDrawer', 'cid']);
const createForm = reactive<chapterForm>({
    cid: props.cid,
    name: '高等数学第一节课',
    introduction: '这是高等数学的第一节课',
    video: ''
})

// 上传视频
import type { UploadProps } from 'element-plus'
import { useTokenStore } from '@/stores/token';
import { getPoint } from '@/api/point';
import { usePointStore } from '@/stores/point';
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!rawFile.type.includes('video/')) {
        ElMessage.error('请上传视频文件')
        return false
    } else if (rawFile.size / 1024 / 1024 > 50) {
        ElMessage.error('视频大小请不要超过 50MB!')
        return false
    }
    return true
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response
) => {
    createForm.video = response.data;//返回url

}
//关于知识点和题目的选择
let selectPoint = ref([])
const options = ref<any[]>([]);
const allpoints = ref<pointForm[]>()
const getTableDate = async () => {
    const res = await getPoint();
    usePointStore().setPoint(res.data);
    let knowledgePoints: pointWithQuestionsForm[] = res.data;
    allpoints.value = res.data;
    // 渲染树形选择器时需要的数据格式
    const formattedOptions = knowledgePoints.map(point => {
        const children = point.questions.map(question => ({
            value: question.id,
            label: question.content,
        }));

        // 只有存在子节点时才返回父节点对象
        if (children.length > 0) {
            return {
                value: 'p' + point.id.toString(),
                label: point.name,
                children: children,
            };
        }
        // 不存在子节点时返回 null
        return null;
    }).filter(point => point !== null);
    options.value = formattedOptions;
}
// 树形选择器的值
const questions = ref()
onMounted(() => {
    getTableDate();
})

function submitChapter() {
    ElMessageBox.confirm(`确认添加吗？`)
        .then(async () => {
            // 新建习题发送回去的数据
            const newChapterForm: chapterRequest = {
                chapter: createForm,
                pointIds: selectPoint.value,
                questionIds: questions.value
            }
            let res = await createChapter1(newChapterForm)
            ElMessage.success("添加成功")
            // let result = await createChapter(createForm);
            // ElMessage.success(result.data)
            console.log("fasonggg,", newChapterForm);

            props.closechaDrawer();
            window.location.reload();
        })
        .catch(() => {
            console.error();
        })
}
</script>

<template>
    <div class="main">
        <el-form>
            <el-form-item>
                <el-upload drag action=" /api/course/upload" :headers="{ Authorization: useTokenStore().token }"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <el-icon style="font-size: 40px;color:cadetblue;"><upload-filled /></el-icon>
                    <div style="color: cadetblue;">
                        拖拽上传 or <em>点击上传</em>
                    </div>
                    <template #tip>
                        <div style="color: cadetblue;">
                            视频大小请不要超过 50MB
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-input v-model="createForm.name" placeholder="新建章节" style="margin-bottom: 10px;" />
                <el-input type="textarea" v-model="createForm.introduction" placeholder="章节简介"
                    style="margin-bottom: 10px;" />
            </el-form-item>
            <el-form-item>
                <!-- 选择章节对应知识点 -->
                <el-select multiple :max-collapse-tags="5" v-model="selectPoint" placeholder="选择本章所用知识点"
                    style="margin-bottom: 10px;">
                    <el-option v-for="item in allpoints" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <!-- 树形选择-选择章节需要的习题 -->
                <el-tree-select v-model="questions" :data="options" multiple :render-after-expand="false"
                    placeholder="选择本章课后习题" />
            </el-form-item>
            <el-form-item>
                <el-button @click="submitChapter()">添加</el-button>
                <el-button @click="closechaDrawer()">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<style scoped></style>
